/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.frontendproject.changedetect.generate.stepexecute;

import com.inspur.edp.lcm.metadata.api.entity.OperationEnum;
import com.inspur.edp.lcm.metadata.api.service.MetadataProjectService;
import com.inspur.edp.web.common.entity.TerminalType;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.frontendproject.changedetect.ChangeDetectExecuteType;
import com.inspur.edp.web.frontendproject.changedetect.ExcludePathEntity;
import com.inspur.edp.web.frontendproject.changedetect.context.ChangeDetectContext;
import com.inspur.edp.web.frontendproject.changedetect.generate.AbstractGenerateChangeDetectStepExecuteService;
import com.inspur.edp.web.frontendproject.changedetect.step.ChangeDetectStepExecuteResult;
import com.inspur.edp.web.frontendproject.changedetect.step.ChangeDetectStepExecuteService;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Title: WebDevFileChangeStepExecuteImpl
 * @Description: 文件变更检测步骤
 * @Author: Noah
 * @Version: V1.0
 * @Create: 2022/6/21 16:51
 */
public class FileChangeStepExecuteImpl extends AbstractGenerateChangeDetectStepExecuteService implements ChangeDetectStepExecuteService {
    /**
     * 步骤执行器参数 生成对应文件变更检测执行
     *
     * @param context 变更检测上下文参数
     * @return 文件变更执行结果
     */
    @Override
    public ChangeDetectStepExecuteResult execute(ChangeDetectContext context) {
        ChangeDetectStepExecuteResult changeDetectStepExecuteResult = ChangeDetectStepExecuteResult.getPassResult(ChangeDetectExecuteType.Generate);
        String srcWebDevPath = this.getSrcWebDevPath(context);
        if (!FileUtility.exists(srcWebDevPath)) {
            changeDetectStepExecuteResult.setUnPassReason(this.generateReasonWithPrefix(context.getTerminalType().getWebDevPathName() + "目录不存在"));
            return changeDetectStepExecuteResult;
        }

        MetadataProjectService metadataProjectService = this.getMetadataProjectService();
        // 判断webdev文件是否包含变更 主要目标是jit的排除项文件
        // webdev  目录判断 排除package.json 文件
        List<ExcludePathEntity> excludePathEntityList = this.getNeedExcludePathList(context);
        boolean webDevFileChangeFlag = metadataProjectService.isFileChanged(srcWebDevPath, OperationEnum.WEB_GENERATE, (dir, name) -> {
            // 如果进行了排除 那么不进行目录检测
            boolean matchExcludePathFlag = excludePathEntityList.stream().anyMatch(t -> t.getParentDir() != null &&
                    t.getParentDirFile().equals(dir) &&
                    Objects.equals(t.getName(), name));
            return !matchExcludePathFlag;
        });
        if (webDevFileChangeFlag) {
            changeDetectStepExecuteResult.setUnPassReason(this.generateReasonWithPrefix(context.getTerminalType().getWebDevPathName() + "存在文件变更"));
            return changeDetectStepExecuteResult;
        }

        String srcAppPath = this.getSrcAppPath(context);

        if (context.getTerminalType() == TerminalType.PC) {
            // 判断源代码工程目录是否存在
            String srcAppProjectsPath = FileUtility.combine(srcAppPath, "projects");
            if (!FileUtility.exists(srcAppProjectsPath)) {
                changeDetectStepExecuteResult.setUnPassReason(this.generateReasonWithPrefix("ts源代码目录不存在"));
                return changeDetectStepExecuteResult;
            }

            // 检查angular.json 文件是否存在
            String angularJsonPath = FileUtility.combine(srcAppPath, this.angularJsonName);
            if (!FileUtility.exists(angularJsonPath)) {
                changeDetectStepExecuteResult.setUnPassReason(this.generateReasonWithPrefix("angular.json文件不存在"));
                return changeDetectStepExecuteResult;
            }

            // tsconfig.json 文件是否存在
            String tsConfigJsonPath = FileUtility.combine(srcAppPath, this.tsConfigJsonName);
            if (!FileUtility.exists(tsConfigJsonPath)) {
                changeDetectStepExecuteResult.setUnPassReason(this.generateReasonWithPrefix("tsconfig.json文件不存在"));
                return changeDetectStepExecuteResult;
            }

            // 判断app.config.json 文件是否存在
            String appConfigJsonPath = this.getAppConfigJsonPath(context);
            if (!FileUtility.exists(appConfigJsonPath)) {
                changeDetectStepExecuteResult.setUnPassReason(this.generateReasonWithPrefix("app.config.json文件不存在"));
                return changeDetectStepExecuteResult;
            }
            // 检测app.config.json 文件是否发生变更
            boolean appConfigJsonChangedFlag = metadataProjectService.isFileChanged(appConfigJsonPath, OperationEnum.WEB_GENERATE);
            if (appConfigJsonChangedFlag) {
                changeDetectStepExecuteResult.setUnPassReason(this.generateReasonWithPrefix("app.config.json文件发生变更"));
                return changeDetectStepExecuteResult;
            }
        } else {
            // 由于移动表单在生成时创建node_modules
            String nodeModulesPath = FileUtility.combine(srcAppPath, "node_modules");
            if (!FileUtility.exists(nodeModulesPath)) {
                changeDetectStepExecuteResult.setUnPassReason(this.generateReasonWithPrefix("node_modules目录不存在"));
                return changeDetectStepExecuteResult;
            }
        }

        // package.json 文件是否存在
        String packageJsonPath = FileUtility.combine(srcAppPath, this.packageJsonName);
        if (!FileUtility.exists(packageJsonPath)) {
            changeDetectStepExecuteResult.setUnPassReason(this.generateReasonWithPrefix("package.json文件不存在"));
            return changeDetectStepExecuteResult;
        }

        return changeDetectStepExecuteResult;
    }

    /**
     * 针对元数据的变更回写动作
     *
     * @param context
     * @return
     */
    @Override
    public ChangeDetectStepExecuteResult updateChangeset(ChangeDetectContext context) {
        ChangeDetectStepExecuteResult stepExecuteResult = ChangeDetectStepExecuteResult.getPassResult(ChangeDetectExecuteType.Generate);

        MetadataProjectService metadataProjectService = this.getMetadataProjectService();

        // 回写webdev的变更
        // webdev  目录判断 排除package.json 文件
        List<ExcludePathEntity> excludePathEntityList = this.getNeedExcludePathList(context);
        metadataProjectService.updateFileChanges(this.getSrcWebDevPath(context), OperationEnum.WEB_GENERATE,(dir, name)->{
            // 如果进行了排除 那么不进行目录检测
            boolean matchExcludePathFlag = excludePathEntityList.stream().anyMatch(t -> t.getParentDir() != null &&
                    t.getParentDirFile().equals(dir) &&
                    Objects.equals(t.getName(), name));
            return !matchExcludePathFlag;
        });
        // 回写app.config.json 文件变更
        if (context.getTerminalType() == TerminalType.PC) {
            metadataProjectService.updateFileChanges(this.getAppConfigJsonPath(context), OperationEnum.WEB_GENERATE);
        }

        return stepExecuteResult;
    }

    /**
     * 不检测文件变化
     *
     * @param context
     * @return
     */
    private List<ExcludePathEntity> getNeedExcludePathList(ChangeDetectContext context) {
        List<ExcludePathEntity> excludePathList = new ArrayList<>();
        String webDevPath = this.getSrcWebDevPath(context);
        ExcludePathEntity excludeWebDevPackageJsonPathEntity = new ExcludePathEntity(webDevPath, "package.json");
        excludePathList.add(excludeWebDevPackageJsonPathEntity);
        return excludePathList;
    }
}
